import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import layout from '@/views/layout'
import article from '@/views/article'
import search from '@/views/search'
import SearchResults from '@/views/search/SearchResults'
import home from '@/views/home'
import ask from '@/views/ask'
import video from '@/views/video'
import mine from '@/views/mine'
import MyChat from '@/views/mine/MyChat'
import UserEdit from '@/views/mine/UserEdit'
import store from '@/store'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  { path: '', redirect: '/home' },
  { name: 'login', path: '/login', component: login },
  { name: 'article', path: '/article/:id', component: article },
  { name: 'search', path: '/search', component: search },
  { name: 'SearchResults', path: '/search/SearchResults', component: SearchResults },
  { name: 'MyChat', path: '/mine/chat', component: MyChat },
  {
    name: 'UserEdit',
    path: '/mine/edit',
    component: UserEdit,
    meta: {
      needLogin: true
    }
  },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      { name: 'home', path: '/home', component: home },
      { name: 'ask', path: '/ask', component: ask },
      {
        name: 'video',
        path: '/video',
        component: video
      },
      {
        name: 'mine',
        path: '/mine',
        component: mine,
        meta: {
          needLogin: true
        }
      }
    ]
  }
]
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, resolve, reject) {
  if (resolve || reject) return originalPush.call(this, location, resolve, reject)
  return originalPush.call(this, location).catch((e) => { })
}

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    if (store.state.user.tokenObj.token) {
      next()
    } else {
      Toast('请先登录')
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else {
    next()
  }
})

export default router
